<?php
namespace App\Controller;

use Think\Cache;

class IndentController extends ApiController
{
    /**
     * 余额支付生成订单
     */
    public function balance_payment()
    {
        if(IS_POST) {
            $user_id=I('post.user_id');
            if (empty($user_id)||!is_numeric($user_id)) {
                json_Response('-200','请先登录','null',2);
            }
            $count=D('User')->where("id={$user_id}")->count();
            if(!$count){
                json_Response('-200','请先登录','null',2);
            }
            $delivery_id = I('post.delivery_id');
            if (empty($delivery_id)||!is_numeric($delivery_id)) {
                json_Response('-200','请先选择收货地址','null',2);
            }
            $count1=D('Gongying_delivery')->where(array(
                'id'=>array('eq',$delivery_id),
                'user_id'=>array('eq',$user_id)
            ))->count();
            if (!$count1) {
                json_Response('-200','请先选择收货地址','null',2);
            }
            $flag = I('post.flag');//1是购物车，0是立即购买
            if (empty($flag)||!is_numeric($flag)||($flag!=1&&$flag!=2)) {
                json_Response('-200','参数错误','null',2);
            }
            if($flag==1){
                $cart_id = I('post.cart_id');
                if (empty($cart_id)) {
                    json_Response('-200','参数错误','null',2);
                }
                $cart_id=str_replace("，",",",$cart_id);
                $delivery = D('Gongying_delivery')->find($delivery_id);//收货地址
                $data = D('Cart')->where("id in({$cart_id})")->select();//从购物车选择结算的商品的信息
                if (empty($data)) {
                    json_Response('-200','参数错误','null',2);
                }
                $arr['user_id'] = $user_id;
                $arr['user_phone'] = D('User')->where("id = {$user_id}")->getField('phone');//下单会员
                $arr['shipping_address'] = $delivery['shipping_address'];
                $arr['tell'] = $delivery['tell'];//收货人电话
                $arr['city_rel'] = $delivery['city_rel'];
                $arr['city_town'] = $delivery['city_town'];
                $arr['city_classify'] = $delivery['city_classify'];
                $arr['consignee'] = $delivery['consignee'];
                $arr['order_number'] = time().rand(10000,99999);
                $shiwu = M();
                foreach ($data as $v)
                {
                    //判断自营
                    if($v['supplier_id']!=0)
                    {
                        $goods = D('Goods')->find($v['goods_id']);
                        $arr['factory_price'] = $goods['goods_purchasing']*$v['number'];//进价
                        $arr['total_price'] = $goods['goods_price']*$v['number'];//卖价
                        $arr['supplier_id'] = $v['supplier_id'];//供应人
                        $arr['supplier_name'] = D('Gongying_user')->where("id = {$v['supplier_id']}")->getField('company_name');

                        $price = D('Goodspic')->where("goods_id = {$v['goods_id']} and status=0")->getField('picture_origin');
                        $arr['picture_small'] = $price;
                    }else
                    {
                        $goods = D('Seller_selfgoods')->find($v['goods_id']);
                        $arr['factory_price'] = $goods['goods_purchasing']*$v['number'];//进价
                        $arr['total_price'] = $goods['goods_price']*$v['number'];//卖价
                        $arr['supplier_id'] = 0;//供应人
                        $price = D('Goodspic')->where("goods_id = {$v['goods_id']}  and status=1")->getField('picture_origin');
                        $arr['picture_small'] = $price;
                    }

                    $arr['seller_id'] = $v['seller_id'];//商家
                    $arr['seller_name'] = D('Seller_user')->where("id = {$v['seller_id']}")->getField('enterprise');

                    $city = D('Seller_user')->where("id = {$v['seller_id']}")->getField('city_id');
                    $arr['city_user_id'] = D('City_user')->where("city_id = {$city} and is_host = 1 ")->getField('id');
                    if(empty($arr['city_user_id'])){
                        $arr['city_user_id'] = 1;
                    }
                    $arr['create_time'] = time();
                    $arr['indent_number'] = $v['number'];
                    $arr['goods_name'] = $goods['goods_name'];
                    $arr['goods_shape'] = $goods['goods_shape'];
                    $attr = M('GoodsAttr')->alias('a1')->join('left join tpshop_attribute a2 on a1.attr_id = a2.attr_id')->where("a1.id in ({$v['goods_attr_ids']})")->select();
                    $arr['details_attr']='';
                    foreach ($attr as $vv){
                        $arr['details_attr'] .= $vv['attr_name'].':'.$vv['attr_value'].',';
                    }
                    $arr['goods_partition'] = $goods['goods_partition'];
                    $arr['seller_goodsid'] =$v['goods_id'];
                    //判断库存，自营
                    if($v['supplier_id']!=0)
                    {
                        $num = D('Goods')->where("id = {$v['goods_id']}")->getField('goods_number');
                        if($num<$v['number'])
                        {
                            json_Response('-200','库存不足，请重新选择商品！','null',2);
                        }
                    }else{
                        $num = D('Seller_selfgoods')->where("id = {$v['goods_id']}")->getField('goods_number');
                        if($num<$v['number'])
                        {
                            json_Response('-200','库存不足，请重新选择商品！','null',2);
                        }
                    }
                    //生成订单前，开启事务
                    $shiwu->startTrans();
                    $resll = D('Gongying_indent')->add($arr);//添加订单
                    if (!$resll)
                    {
                        json_Response('-200','生成订单失败','null',2);
                    }
                    //减库存
                    if($v['supplier_id']!=0){
                        $ret=D('Goods')->where(array(
                            'id'=>array('eq',$v['goods_id'])
                        ))->setDec('goods_number',$v['number']);
                        if (!$ret)
                        {
                            json_Response('-200','生成订单失败','null',2);
                        }
                    }else{
                        $ret=D('Seller_selfgoods')->where(array(
                            'id'=>array('eq',$v['goods_id'])
                        ))->setDec('goods_number',$v['number']);
                        if (!$ret)
                        {
                            json_Response('-200','生成订单失败','null',2);
                        }
                    }

                }
                //删除购物车已下单的商品
                $res = D('Cart')->where("id in({$cart_id})")->delete();

                if($res === false)
                {
                    json_Response('-200','删除购物车原商品失败','null',2);

                }

                $order_number = D('Gongying_indent')->where("id = {$resll}")->getField('order_number');//获得订单购买数量
                $arr=['order_number'=>$order_number];
                //所有操作完成后，提交事务
                $shiwu->commit();
                json_Response('200','生成订单成功',$arr,3);

            }elseif($flag==2){
                //立即购买
                $delivery = D('Gongying_delivery')->find($delivery_id);//收货地址
//                $data = D('Cart')->where("id in({$cart_id})")->select();//从购物车选择结算的商品的信息
                $arr['user_id'] = $user_id;
                $arr['user_phone'] = D('User')->where("id = {$user_id}")->getField('phone');//下单会员
                $arr['shipping_address'] = $delivery['shipping_address'];
                $arr['tell'] = $delivery['tell'];//收货人电话
                $arr['city_rel'] = $delivery['city_rel'];
                $arr['city_town'] = $delivery['city_town'];
                $arr['city_classify'] = $delivery['city_classify'];
                $arr['consignee'] = $delivery['consignee'];
                $arr['order_number'] = time().rand(10000,99999);
                $shiwu = M();

                    $data=I('post.');
                    //goods_id,number,supplier_id,seller_id,goods_attr_ids
                    if (empty($data['goods_id'])||empty($data['number'])||$data['supplier_id']==""||empty($data['seller_id'])||empty($data['goods_attr_ids'])) {
                        json_Response('-200','参数错误1','null',2);
                    }
                    if (!is_numeric($data['goods_id'])||!is_numeric($data['number'])||!is_numeric($data['supplier_id'])||!is_numeric($data['seller_id'])) {
                        json_Response('-200','参数错误','null',2);
                    }
                    //判断自营
                    if($data['supplier_id']!=0)
                    {
                        $goods = D('Goods')->find($data['goods_id']);
                        $arr['factory_price'] = $goods['goods_purchasing']*$data['number'];//进价
                        $arr['total_price'] = $goods['goods_price']*$data['number'];//卖价
                        $arr['supplier_id'] = $data['supplier_id'];//供应人
                        $arr['supplier_name'] = D('Gongying_user')->where("id = {$data['supplier_id']}")->getField('company_name');

                        $price = D('Goodspic')->where("goods_id = {$data['goods_id']} and status=0")->getField('picture_origin');
                        $arr['picture_small'] = $price;
                    }else
                    {
                        $goods = D('Seller_selfgoods')->find($data['goods_id']);
                        $arr['factory_price'] = $goods['goods_purchasing']*$data['number'];//进价
                        $arr['total_price'] = $goods['goods_price']*$data['number'];//卖价
                        $arr['supplier_id'] = 0;//供应人
                        $price = D('Goodspic')->where("goods_id = {$data['goods_id']}  and status=1")->getField('picture_origin');
                        $arr['picture_small'] = $price;
                    }

                    $arr['seller_id'] = $data['seller_id'];//商家
                    $arr['seller_name'] = D('Seller_user')->where("id = {$data['seller_id']}")->getField('enterprise');

                    $city = D('Seller_user')->where("id = {$data['seller_id']}")->getField('city_id');
                    $arr['city_user_id'] = D('City_user')->where("city_id = {$city} and is_host = 1 ")->getField('id');
                    if(empty($arr['city_user_id'])){
                        $arr['city_user_id'] = 1;
                    }
                    $arr['create_time'] = time();
                    $arr['indent_number'] = $data['number'];
                    $arr['goods_name'] = $goods['goods_name'];
                    $arr['goods_shape'] = $goods['goods_shape'];
                    $attr = M('GoodsAttr')->alias('a1')->join('left join tpshop_attribute a2 on a1.attr_id = a2.attr_id')->where("a1.id in ({$data['goods_attr_ids']})")->select();
                    $arr['details_attr']='';
                    foreach ($attr as $vv){
                        $arr['details_attr'] .= $vv['attr_name'].':'.$vv['attr_value'].',';
                    }
                    $arr['goods_partition'] = $goods['goods_partition'];
                    $arr['seller_goodsid'] =$data['goods_id'];
                    //判断库存，自营
                    if($data['supplier_id']!=0)
                    {
                        $num = D('Goods')->where("id = {$data['goods_id']}")->getField('goods_number');
                        if($num<$data['number'])
                        {
                            json_Response('-200','库存不足，请重新选择商品！','null',2);
                        }
                    }else{
                        $num = D('Seller_selfgoods')->where("id = {$data['goods_id']}")->getField('goods_number');
                        if($num<$data['number'])
                        {
                            json_Response('-200','库存不足，请重新选择商品！','null',2);
                        }
                    }
                    //生成订单前，开启事务
                    $shiwu->startTrans();
                    $resll = D('Gongying_indent')->add($arr);//添加订单
                    if (!$resll)
                    {
                        json_Response('-200','生成订单失败','null',2);
                    }
                    //减库存
                    if($data['supplier_id']!=0){
                        $ret=D('Goods')->where(array(
                            'id'=>array('eq',$data['goods_id'])
                        ))->setDec('goods_number',$data['number']);
                        if (!$ret)
                        {
                            json_Response('-200','生成订单失败','null',2);
                        }
                    }else{
                        $ret=D('Seller_selfgoods')->where(array(
                            'id'=>array('eq',$data['goods_id'])
                        ))->setDec('goods_number',$data['number']);
                        if (!$ret)
                        {
                            json_Response('-200','生成订单失败','null',2);
                        }
                    }
                $order_number = D('Gongying_indent')->where("id = {$resll}")->getField('order_number');//获得订单购买数量

                $arr=['order_number'=>$order_number];
                //所有操作完成后，提交事务
                $shiwu->commit();
                json_Response('200','生成订单成功',$arr,3);

            }

        }else{
            json_Response('-200','传输失败','null',2);
        }
    }
    /**
     * 余额支付
     */
    public function balance_accounts(){
        if(IS_POST) {
            $user_id=I('post.user_id');
            if (empty($user_id)||!is_numeric($user_id)) {
                json_Response('-200','请先登录','null',2);
            }
            $count=D('User')->where("id={$user_id}")->count();
            if(!$count){
                json_Response('-200','请先登录','null',2);
            }

            $order_number=I('post.order_number');
            if (empty($order_number)) {
                json_Response('-200','参数错误','null',2);
            }
            $Gongying_indent=D('Gongying_indent');
            //获取用户信息
            $userData=D('User')->find($user_id);
            $shiwu = M();

                //判断订单状态
                $status=$Gongying_indent
                    ->where("order_number =$order_number")
                    ->getField("price_status");
                if($status==1)
                {
                    json_Response('-200','订单已提交，请不要重复提交','null',2);
                }
                //获得应支付的总价
                $data=$Gongying_indent
                    ->where("order_number =$order_number")
                    ->getField("SUM(total_price) total");

                //判断余额是否充足

                if($data>$userData['cash'])
                {
                    json_Response('-200','余额不足，请即时充值!','null',2);

                }
                //判断二级密码
                $password_two=I('post.password_two');
                if (empty($password_two)) {
                    json_Response('-200','参数错误','null',2);
                }
                if($userData['password_two'] != md516($password_two))
                {
                    json_Response('-200','你的支付密码错误，请重试','null',2);
                }
                //扣余额时，开启事务
                $shiwu->startTrans();
                $packetData = $Gongying_indent
                    ->field('indent_number,seller_goodsid,supplier_id,seller_id')
                    ->where("order_number=$order_number")
                    ->select();
                foreach($packetData as $k=>$v){
                    //判断是否是自营商品
                    if($v['supplier_id']!=0){
                        $result[$k]=D("Seller_goods")
                            ->where(array('goods_id'=>$v['seller_goodsid'],'seller_id'=>$v['seller_id']))
                            ->find();
                        $result[$k]['indent_number'] = $v['indent_number'];
                    }else{
                        $result[$k]=D('Seller_selfgoods')
                            ->where("id={$v['seller_goodsid']}")
                            ->find();
                        $result[$k]['indent_number'] = $v['indent_number'];
                    }
                }
                //获取奖励红包的总金额
                foreach ($result as $k=>$v){
                    $total_packet[]=$v['goods_packet']*$v['indent_number'];
                }
                $total_packet=array_sum($total_packet);

                //获取该用户账户当前的红包金额
                $red_packet=$userData['red_packet'];
                if($red_packet>=$data){
                    //红包余额大于购买商品的总金额
                    $new['cash']=$userData['cash'];
                    $new['red_packet']=$userData['red_packet']+$total_packet-$data;
                }else{
                    //红包余额小于购买商品的总金额
                    $new['cash']=$userData['cash']-$data+$red_packet;
                    $new['red_packet']=$total_packet;
                }
                //更新会员的账户余额
                $ret=D('User')
                    ->where(array('id'=>array('eq',$user_id)))
                    ->save($new);
                if($ret === false){
                    json_Response('-200','扣款失败，请重试!','null',2);

                }
                //余额消费记录表添加数据
                $goodsData=$Gongying_indent
                    ->field('goods_name,details_attr,indent_number,supplier_id,seller_id')
                    ->where(array(
                        'order_number'=>array('eq',$order_number)
                    ))
                    ->select();
                $des='';
                $sup='';
                $sel='';
                foreach ($goodsData as $k=>$v)
                {
                    $des.=$v['goods_name'].'规格'.$v['details_attr'].'数量'.$v['indent_number'];
                    $sup.=$v['supplier_id'];
                    $sel.=$v['seller_id'];
                }
                $bData['accounts_number']=$data;
                $bData['accounts_time']=date("Y-m-d H:i:s",time());
                $bData['information']='订单号：'.$order_number.'买家：'.session('qt_info.username').'购买商品：'.$des.'消费'.$data.'元人民币';
                $bData['supplier_id']=$sup;
                $bData['seller_id']=$sel;
                $bData['user_id']=$user_id;
                $bData_res=D('Purchase')->add($bData);
                if (!$bData_res)
                {
                    json_Response('-200','余额消费记录表添加失败！','null',2);

                }
                //修改订单状态
                $ret=D('Gongying_indent')
                    -> where("order_number={$order_number}")
                    ->setField('price_status',1);
                if (!$ret)
                {
                    json_Response('-200','支付失败！','null',2);
                }
                $retData=$Gongying_indent
                    ->field('indent_number,seller_goodsid,seller_id,supplier_id')
                    ->where("order_number=$order_number")
                    ->select();
                //总销量的添加
                $result=[];
                foreach ($retData as $k=>$v)
                {
                    if($v['supplier_id']!=0)
                    {
                        $result[]=D('Seller_goods')
                            ->where(array('goods_id'=>$v['seller_goodsid'],'seller_id'=>$v['seller_id']))
                            ->setInc('sall_numbe',$v['indent_number']);
                    }else{
                        $result[]=D('Seller_selfgoods')
                            ->where(array('id'=>$v['seller_goodsid'],'seller_id'=>$v['seller_id']))
                            ->setInc('sall_numbe',$v['indent_number']);
                    }
                }
//            $this->ajaxReturn($result);die;
                if (in_array('0',$result))
                {
                    json_Response('-200','销量添加失败，支付失败！','null',2);

                }else{
                    //支付成功
                    //所有操作完成后，提交事务
                    $shiwu->commit();
                    json_Response('200','支付成功！',null,2);
                }

        }else{
            json_Response('-200','传输失败','null',2);
        }
    }
    /**
     * 获得会员信息
     */
    public function user_info()
    {
        if (IS_POST) {
            $user_id = I('post.user_id');
            if (empty($user_id) || !is_numeric($user_id)) {
                json_Response('-200', '参数错误', 'null', 2);
            }
            $count = D('User')->where("id={$user_id}")->count();
            if (!$count) {
                json_Response('-200', '参数错误', 'null', 2);
            }
            $data = D('User')->find($user_id);
            json_Response('200', '传输成功', $data, 1);

        } else {
            json_Response('-200', '传输失败', 'null', 2);
        }
    }


}
